# 这里使用coding:utf-8的注释，可以解决中文注释报错的问题
# 试着把下面的一行去掉，然后访问地址http://localhost:8000/test/time/plus/12/，则会看到报错信息
# coding:utf-8
# 甚至只要注释中包含"coding:utf-8"的字符串，都会避免中文报错问题，很有趣

from django.shortcuts import HttpResponse
from django.http import Http404
from datetime import *
from django.template.loader import get_template
from django.template import Context
from django.shortcuts import render_to_response
import MySQLdb

# Create your views here.
def test_hello(request):
    return HttpResponse("Hello World")

def test_current_date(request):
    now = datetime.now()
    html = "<html><body>It's now %s.</body></html>" % now
    return HttpResponse(html)

def test_hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.now() + timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

def test_hours_ahead_use_template(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.now() + timedelta(hours=offset)
    t = get_template("testTemplate.html")
    html = t.render(Context({'offset':offset, 'dt':dt}))
    return HttpResponse(html)

def test_hours_ahead_use_template_and_render_to_response(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.now() + timedelta(hours=offset)
    # return render_to_response('testTemplate.html', {'offset':offset, 'dt':dt})

    # locals() 返回当前点所有的变量值，在这里locals()返回值中就包含offset变量和dt变量，模板在解析的时候就会自动使用这些变量值
    return render_to_response('testTemplate.html', locals())

def test_person_list(request):
    db = MySQLdb.connect(user='root', db='test', passwd='root', host='localhost')
    cursor = db.cursor()
    cursor.execute('select name, age from person order by id')
    names = [row[0] for row in cursor.fetchall()]
    db.close()
    return render_to_response('testPersonList.html', {'names':names})